<script setup>
import {onUnmounted, ref} from 'vue';
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";
import http from "@/request/Http.js";


const router = useRouter();
//表单信息
const registerForm = ref({
  username: '',
  password: '',
  rePassword: '',
  email: '',
  code: ''
})

//获取组件实例的对象 用组件实例对象调用内部属性与方法获取表单校验转态
const registerFormRef = ref()

//===========注册============
//点击注册
const register = async () => {
  //主动调用 表单的调用
  console.log(registerFormRef.value)
  registerFormRef.value.validate(async (val) => {
    if (!val) {
      //val 是一个布尔值  validate 会主动校验表单规则 返回 通过或者失败
      ElMessage.error("请完善表单信息")
      return
    }
    //先验证验证码
    const isCodeValid = await verifyCaptcha(
        registerForm.value.email,
        registerForm.value.code
    )
    if (!isCodeValid) {
      return
    }

    //验证密码是否一致
    if (registerForm.value.password !== registerForm.value.rePassword) {
      //判断新密码和重复密码是否一致，不一致则提示
      ElMessage.error("新密码和确认密码不一致，修改失败")
      return
    }
    try {
      //发送注册请求
      const response = await http.post("/user/register", registerForm.value)
      if (response.code === 200) {
        ElMessage.success("成功注册")
        //重置表单
        registerFormRef.value.resetFields()
        //跳转登录界面
        router.push('/login')
      } else {

        ElMessage.error("注册失败" + response.msg)
      }
    } catch (error) {
      console.error('注册错误:', error)
      ElMessage.error("注册失败，请重试")
    } finally {
      isSubmitting.value = false
    }
  })
};

//==============规则=============
//定义表单校验 规则列表
const rules = {
  //指定一个字段，指定字段的规则
  username: [
    //非空校验(校验触底规则 触发后的提示信息 触发规则项)
    {required: true, message: "请输入用户名", trigger: 'blur'},
    //长度校验
    {min: 3, max: 22, message: "长度在3-22个字符之间", trigger: 'blur'}
  ],
  password: [
    //非空校验(校验触底规则 触发后的提示信息 触发规则项)
    {required: true, message: "请输入密码", trigger: 'blur'},
    //长度校验
    {min: 6, max: 22, message: "密码长度在6-22个字符之间", trigger: 'blur'},
    //密码强度校验
    {pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/, message: "密码必须包含字母和数字", trigger: 'blur'}
  ],
  rePassword: [
    //非空校验(校验触底规则 触发后的提示信息 触发规则项)
    {required: true, message: "请输入确定密码", trigger: 'blur'},
    //长度校验
    {min: 6, max: 22, message: "密码长度在6-22个字符之间", trigger: 'blur'},
  ],
  email: [
    //非空校验(校验触底规则 触发后的提示信息 触发规则项)
    {required: true, message: "请输入邮箱地址", trigger: 'blur'},
    //格式校验
    {pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: "请输入正确的邮箱格式", trigger: 'blur'}
  ],
  code: [
    //非空校验(校验触底规则 触发后的提示信息 触发规则项)
    {required: true, message: "验证码不能为空", trigger: 'blur'},
  ]
}

//============去登录========
//跳转登录页面
const login = () => {
  router.push('/login')
}

//===========根据邮箱获取验证码=======
// 状态管理
const countdown = ref(0) // 倒计时
const timeLeft = ref(0)  // 验证码剩余时间
const isSending = ref(false)
const isSubmitting = ref(false)
let timer = null

// 清理定时器
onUnmounted(() => {
  if (timer) clearInterval(timer)
})

// 发送验证码
const getCode = async () => {
  if (!registerForm.value.email) {
    ElMessage.error('请输入邮箱')
    return
  }
  isSending.value = true
  try {
    const params = new URLSearchParams()
    params.append('email', registerForm.value.email)
    const response = await http.post('/captcha/emailCode', params)
    console.log(response)
    if (response.code === 200) {
      ElMessage.success('验证码发送成功')
      startCountdown()
      startCodeExpireTimer()
    } else {
      ElMessage.error(response.message || '验证码发送失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请重试')
  } finally {
    isSending.value = false
  }
}

// 开始60秒倒计时
const startCountdown = () => {
  countdown.value = 60
  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}
// 开始验证码有效期倒计时（5分钟）
const startCodeExpireTimer = () => {
  timeLeft.value = 300
  const expireTimer = setInterval(() => {
    timeLeft.value--
    if (timeLeft.value <= 0) {
      clearInterval(expireTimer)
      ElMessage.warning('验证码已过期，请重新获取')
    }
  }, 1000)
}

//检验验证码是否正确
const verifyCaptcha = async (email, code) => {
  //检验验证码是否正确，正确才可进行组成，错误直接提示
  try {
    const params = new URLSearchParams();
    params.append('email', email)
    params.append('code', code)
    const response = await http.post('/captcha/verifyCode', params)
    console.log(response)
    //验证码码是否正确
    if (response.code === 200) {
      ElMessage.success('验证成功')
      countdown.value = 0
      timeLeft.value = 0
      return true
    } else {
      ElMessage.error(response.message || '验证失败')
      return false
    }
  } catch (error) {
    console.error('验证码验证错误详情:', error)
    ElMessage.error('网络错误，请重试')
    return false
  }
}

</script>

<template>
  <!-- 外层容器用于居中，并添加渐变背景 -->
  <div class="centered-container">
    <!-- 登录卡片 -->
    <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="rules" class="login-form" label-width="120px">
      <h2 class="form-title">用户注册</h2>
      <!-- 邮箱表单项 -->
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="registerForm.email" placeholder="请输入邮箱" size="large"></el-input>
      </el-form-item>
      <!-- 用户名表单项 -->
      <el-form-item label="用户名" prop="username">
        <el-input v-model="registerForm.username" placeholder="请输入用户名" size="large"></el-input>
      </el-form-item>
      <!-- 密码表单项 -->
      <el-form-item label="密码" prop="password">
        <el-input v-model="registerForm.password" placeholder="请输入密码" show-password size="large"
                  type="password"></el-input>
      </el-form-item>
      <el-form-item label="确定密码" prop="rePassword">
        <el-input v-model="registerForm.rePassword" placeholder="请输入确定密码" show-password size="large"
                  type="password"></el-input>
      </el-form-item>
      <!-- 用户名表单项 -->
      <el-form-item label="验证码" prop="code">
        <el-input v-model="registerForm.code" placeholder="请输入验证码" size="large" style="width: 100px"></el-input>
        <el-button
            :disabled="countdown>0 ||isSending"
            @click="getCode"
        >
          {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
        </el-button>
      </el-form-item>
      <el-form-item v-if="timeLeft>0" class="time-tip">
        验证码有效期剩余：{{ timeLeft }}秒
      </el-form-item>
      <!-- 注册按钮 -->
      <el-form-item>
        <el-button class="login-button" type="primary" @click="register">
          注册
        </el-button>
      </el-form-item>


      <div class="form-footer">
        <el-link type="primary" @click="login">去登录</el-link>
      </div>
    </el-form>

  </div>

</template>

<style scoped>
.form-footer {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.centered-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url("https://img.shetu66.com/2022/08/cutCoverImg/1663065835196923.png");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  padding: 20px;
}


.login-form {
  width: 400px;
  padding: 40px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  /* 柔和阴影 */
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px); /* 磨砂玻璃效果 */
  transition: transform 0.3s ease-in-out;
}

.login-form:hover {
  transform: translateY(-5px); /* 鼠标悬停时轻微上浮 */
}

.form-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-family: 'Arial', sans-serif;
  font-weight: bold;
}

/* 按钮样式 */
.login-button {
  width: 100%;
  font-size: 16px;
  height: 40px;
  border-radius: 8px;
  background-color: #409eff;
  border-color: #409eff;
  transition: all 0.3s ease-in-out;
}

.login-button:hover {
  transform: scale(1.02);
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 输入框样式 */
.el-input {
  border-radius: 8px;
}
</style>
